import uuid
from datetime import datetime, timedelta
from typing import Dict, List, Any

class SessionManager:
    def __init__(self, max_history_length: int = 5, session_timeout_minutes: int = 30):
        """
        初始化会话管理器
        
        参数:
        - max_history_length: 每个会话保留的最大历史消息数
        - session_timeout_minutes: 会话超时时间(分钟)
        """
        self.sessions: Dict[str, Dict[str, Any]] = {}
        self.max_history_length = max_history_length
        self.session_timeout_minutes = session_timeout_minutes

    def create_session(self, user_id: str = None) -> str:
        """
        创建新会话
        
        参数:
        - user_id: 用户标识(可选)
        
        返回:
        - 会话ID
        """
        session_id = str(uuid.uuid4())
        self.sessions[session_id] = {
            "user_id": user_id,
            "created_at": datetime.now(),
            "last_active_at": datetime.now(),
            "history": []
        }
        return session_id

    def get_session(self, session_id: str) -> Dict[str, Any]:
        """
        获取会话
        
        参数:
        - session_id: 会话ID
        
        返回:
        - 会话信息，如果会话不存在或已超时则返回None
        """
        if session_id not in self.sessions:
            return None

        session = self.sessions[session_id]
        # 检查会话是否超时
        if (datetime.now() - session["last_active_at"]).total_seconds() > self.session_timeout_minutes * 60:
            # 会话已超时，删除会话
            del self.sessions[session_id]
            return None

        # 更新会话最后活动时间
        session["last_active_at"] = datetime.now()
        return session

    def update_session(self, session_id: str, query: str, answer: str, metadata: Dict[str, Any] = None) -> bool:
        """
        更新会话历史
        
        参数:
        - session_id: 会话ID
        - query: 用户查询
        - answer: 助手回答
        - metadata: 元数据(可选)
        
        返回:
        - 是否更新成功
        """
        session = self.get_session(session_id)
        if not session:
            return False

        # 添加新的对话历史
        new_history = {
            "query": query,
            "answer": answer,
            "timestamp": datetime.now(),
            "metadata": metadata or {}
        }
        session["history"].append(new_history)

        # 如果历史消息超过最大长度，删除最早的消息
        if len(session["history"]) > self.max_history_length:
            session["history"] = session["history"][-self.max_history_length:]

        return True

    def get_session_history(self, session_id: str) -> List[Dict[str, Any]]:
        """
        获取会话历史
        
        参数:
        - session_id: 会话ID
        
        返回:
        - 会话历史列表，如果会话不存在或已超时则返回空列表
        """
        session = self.get_session(session_id)
        if not session:
            return []
        return session["history"]

    def delete_session(self, session_id: str) -> bool:
        """
        删除会话
        
        参数:
        - session_id: 会话ID
        
        返回:
        - 是否删除成功
        """
        if session_id in self.sessions:
            del self.sessions[session_id]
            return True
        return False

    def cleanup_expired_sessions(self) -> int:
        """
        清理过期会话
        
        返回:
        - 清理的会话数量
        """
        expired_session_ids = []
        current_time = datetime.now()

        for session_id, session in self.sessions.items():
            if (current_time - session["last_active_at"]).total_seconds() > self.session_timeout_minutes * 60:
                expired_session_ids.append(session_id)

        for session_id in expired_session_ids:
            del self.sessions[session_id]

        return len(expired_session_ids)

# 全局会话管理器实例
session_manager = SessionManager()

# 示例用法
if __name__ == "__main__":
    # 创建会话
    session_id = session_manager.create_session()
    print(f"创建新会话: {session_id}")

    # 更新会话
    session_manager.update_session(
        session_id,
        "什么是自然语言处理?",
        "自然语言处理是人工智能的一个分支，专注于计算机与人类语言之间的交互。"
    )

    # 获取会话历史
    history = session_manager.get_session_history(session_id)
    print("会话历史:")
    for item in history:
        print(f"问题: {item['query']}")
        print(f"回答: {item['answer']}")
        print("---")